import actors.Actor
import com.jediflasher.game_server.data.{SuperUserData, WorldData}
import com.jediflasher.game_server.messages.HeaderMessage.ServiceType
import com.jediflasher.game_server.messages.MessageWrapper
import com.jediflasher.game_server.services.{ServiceMovement, ServiceLogin}
import com.jediflasher.game_server.util.log.Logger
import java.io._
import java.net.{SocketException, Socket}

/**
 * User: Obi
 * Date: 11.07.11
 * Time: 22:53
 */

class SocketHandler(socket: Socket, worldData: WorldData) extends Actor {

	private val out = new DataOutputStream(socket.getOutputStream);
	private val in = new DataInputStream(socket.getInputStream);

	private var currentMessageLength = -1;

	private val superUser = new SuperUserData();

	private val serviceLogin: ServiceLogin = new ServiceLogin(out, worldData, superUser);
	private val serviceMovement: ServiceMovement = new ServiceMovement(out, worldData, superUser);

	def act() {
		try {

			println("Client connected from " + socket.getInetAddress + ":" + socket.getPort);

			while (true) {

				if(in.available() > 0) currentMessageLength = in.readInt()
				
				while(currentMessageLength != -1) {
					if(in.available() >= currentMessageLength) {
						sendToService(currentMessageLength);
						currentMessageLength = -1;
					}
				}
			}

			Logger.log("exit");
			socket.close();
		}
		catch {
			case e: SocketException => System.err.println(e);
			case e: IOException => System.err.println(e.getMessage);
			case e => System.err.println("Unknown error " + e);
		}
	}

	private def sendToService(messageLength: Int) {
		Logger.log("input: " +messageLength + " bytes")
		val messageWrapper = new MessageWrapper().read(in);

		messageWrapper.serviceType match {
			case ServiceType.LOGIN  => serviceLogin.process(messageWrapper);
			case ServiceType.MOVEMENT => serviceMovement.process(messageWrapper);
		}
	}
}